package cyan.gf.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;

/**
 * Created by cyan on 2017/2/15.
 * Email:qsyan@vip.qq.com
 */
public class CrudInstance {

  private Connection connection;

  public JdbcProp getJdbcProp() {
    return jdbcProp;
  }

  public void setJdbcProp(JdbcProp jdbcProp) {
    this.jdbcProp = jdbcProp;
  }

  JdbcProp jdbcProp;

  public CrudInstance(Connection connection, JdbcProp jdbcProp) {
    this.connection = connection;
    this.jdbcProp = jdbcProp;
  }

  public void queryAsRow(String queryString, SQLConsumer<ResultSet> rowCallback) {
    PreparedStatement ps;
    try {
      ps = connection.prepareStatement(queryString);
      ResultSet row = ps.executeQuery();
      rowCallback.accept(row);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public void eachRow(String queryString, SQLConsumer<ResultSet> rowCallback) {
    try {
      PreparedStatement ps = connection.prepareStatement(queryString);
      ResultSet row = ps.executeQuery();
      while (row.next()) {
        rowCallback.accept(row);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public void connection(Consumer<Connection> action) {
    action.accept(connection);

  }

  public void destroy() {
    try {
      if (!connection.isClosed()) {
        connection.close();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

}
